import { Component, OnInit } from '@angular/core';
import { InterceptorService } from "../../share/interceptor.service";
import { Router } from "@angular/router";
import { PersonalInfoEntity } from "../../models/personal-info-entity";
import { PersonalManageEntity } from 'app/models/personal-manage-entity';

// 导入数据
import { FileUploader } from 'ng2-file-upload';


@Component({
  selector: 'app-search-all-person',
  templateUrl: './search-all-person.component.html',
  styleUrls: ['./search-all-person.component.css']
})
export class SearchAllPersonComponent implements OnInit {

  //实例化拦截器服务
  constructor(
    private router: Router,
    private http: InterceptorService,
  ) { }

  ngOnInit() {
    this.getData();

    this.getSalaryScope();
    this.getGrade();
    this.getEducation();
    this.getSex();
  }

  queryPersonUrl = 'graduate-web/personalInfo/selectPersonByCombination'; // 组合查询学生信息

  getData() {
    let condition: Condition = this.checkCondition();
    // let url = this.queryPersonUrl; // 对应假数据
    let url = this.queryPersonUrl + '/' + condition.personName + '/' + condition.companyName + '/' + condition.gradeName + '/' + condition.educationName + '/' + condition.salaryRange + '/' + this.page + '/' + this.pageSize; // 组合查询+条件

    this.http.get(url).subscribe(
      res => {
        if (res.json().code == "0000") {
          console.log("**************************页面加载查询信息************************");
          this.data = res.json().data.list;
          console.log(res.json().data.list)
          console.log(res.json().data.total)
          this.total = res.json().data.total;

        }
      }
    );
  }
  private timer;
  private identificateTime: number = 5;


  gradeOptions: string[]; // 期数集合
  educationOptions: string[]; // 学历结合
  salaryScopeOptions: string[]; // 薪资范围集合
  sexOptions: string[]; // 性别集合
  personalInfo: PersonalInfoEntity = new PersonalInfoEntity();//个人信息 // TODO 需要新添加实体
  personManage: PersonalManageEntity = new PersonalManageEntity();//管理实体

  //  条件
  personName: string = ""
  companyName: string;
  gradeName: string;
  salaryRange: string;
  educationName: string;

  //无查询条件时传递 空格|%20
  noContent = "%20";

  // 表格数据
  btnAdd = true;
  btnDelete = false;
  btnEdit = false;
  btnImport = true;
  btnExport = false;
  title = ['姓名', '性别', '期数', '电话', '邮箱', '公司', '月薪'];
  arrbutes = ["name", "sex", 'grade', 'phone', "email", "companyName", "salary"];
  btnList: string[] = ["编辑", "详情"];
  //true为真分页
  paging = true;
  pageSize = 10;
  page = 1;
  sizeList = [5, 10, 15, 50];
  addInfo: any = new Array();
  arr = new Array();
  btnstyle = [
    { "color": "blue" }, { "color": "blue" }]
  total: number;
  data = new Array();
  isCheck = true;

  //自定义编辑列
  operatData(obj: any, editModal: HTMLElement) {
    switch (obj.element.innerText) {
      case "详情":
        this.router.navigateByUrl('/workspace/person-info/search-person-info/search-basic-info');
        this.gainStudentId(obj.data, editModal);
        break;
      case '编辑':
        this.editOpen(obj.data, editModal);
        break;
      default:
        break;
    }
  }

  //获得期数
  getGrade() {
    // let dictName: string;
    let gradeUrl = "graduate-web/dictionary/selectGrade";
    this.http.get(gradeUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.gradeOptions = res.json().data;
          console.log(this.gradeOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [{
            dictName: "5期"
          }, {
            dictName: "6期"
          }, {
            dictName: "7期"
          }, {
            dictName: "8期"
          }, {
            dictName: "9期"
          }, {
            dictName: "10期"
          }, {
            dictName: "11期"
          }];
          this.gradeOptions = data;
        }
      }
    );


  }

  //获得学历
  getEducation() {
    //方案1-假数据
    let data: any[] = [{
      name: "专科"
    }, {
      name: "本科"
    }, {
      name: "硕士"
    }, {
      name: "博士"
    }, {
      name: "博士后"
    }];
    this.educationOptions = data;
    //方案2-后端方法

  }

  //获得月薪
  getSalaryScope() {
    let data: any[] = [{
      name: "1k-10k"
    }, {
      name: "11k-20k"
    }, {
      name: "21k-30k"
    }, {
      name: "31k-40k"
    }, {
      name: ">40k"
    }];
    this.salaryScopeOptions = data;

  }

  getSex() {
    let data: any[] = [{
      id: 'male',
      name: '男'
    }, {
      id: 'female',
      name: '女'
    }
    ];
    this.sexOptions = data;
  }



  combinationSearch() {
    let condition: Condition = this.checkCondition();
    
    this.page = 1;
    
    let url = this.queryPersonUrl + '/' + condition.personName + '/' + condition.companyName + '/' + condition.gradeName + '/' + condition.educationName + '/' + condition.salaryRange + '/' + this.page + '/' + this.pageSize; // 组合查询+条件

    console.log('personName' + this.personName);
    console.log('companyName' + this.companyName);
    console.log(this.gradeName);
    console.log(this.salaryRange);
    console.log(this.educationName);
    // let searchUrl=this.queryPersonUrl; // 对应假数据
    this.http.get(url).subscribe(
      res => {
        if (res.json().code == "0000") {
          if (res.json().message == "无相关条件的查询结果！") {
            console.log(res.json().message);
          } else {
            console.log("**************************查询加载信息************************");
            console.log(res.json().message);
            console.log(res.json().data);

            this.data = res.json().data.list;
            this.total = res.json().data.total;
          }

        } else {
          this.data = Array();

          this.showDialog(res.json().message);
        }
      });
  }

  /**
  * 判断字符串是否为 null或为 "" 值，是则返回true，否返回false
  * @param obj 字符串
  */
  isStrEmpty(obj: string) {
    if (obj == undefined || obj == null || obj.trim() == "") {
      return true;
    }
    return false;
  }


  // 获取组合查询条件的值
  checkCondition(): Condition {
    let condition = new Condition();
    // // 判断名字是否存在
    if (this.isStrEmpty(this.personName)) {
      condition.personName = this.noContent;
    } else {
      condition.personName = this.personName;
    }
    // // 判断公司是否存在
    if (this.isStrEmpty(this.companyName)) {
      condition.companyName = this.noContent;
    } else {
      condition.companyName = this.companyName;
    }
    // // 判断学历是否存在
    if (this.isStrEmpty(this.educationName)) {
      condition.educationName = this.noContent;
    } else {
      condition.educationName = this.educationName;
    }
    // // 判断期数是否存在
    if (this.isStrEmpty(this.gradeName)) {
      condition.gradeName = this.noContent;
    } else {
      condition.gradeName = this.gradeName;
    }
    // // 判断薪资范围是否存在
    if (this.isStrEmpty(this.salaryRange)) {
      condition.salaryRange = this.noContent;
    } else {
      condition.salaryRange = this.salaryRange;
    }
    return condition;
  }


  // 更新页码,更新表格信息
  changepage(data: any) {
    console.log('d=====================================================ata');
    console.log(data);

    //改变页号，更新表格数据
    if (data.page > 0 && data.page < this.total) {
      this.page = data.page;
      // this.getData(url);
    } else {
      this.page = 1;
    }
    this.pageSize = data.pageSize;
    this.getData();

  }

  /*********************添加修改模态框Start************************/

  //打开添加模态框
  addOpen(el: HTMLElement, addModal: HTMLElement) {

    addModal.style.visibility = 'visible';
    document.getElementById('name').focus();

  }

  add(addModal: HTMLElement) {

    if (this.personalInfo == null) {
      this.showDialog("内容为空，请填写数据！");
    }
    if (this.isStrEmpty(this.personalInfo.name)) {
      this.showDialog('姓名不能为空，请填写姓名');
      this.timing();

      return;
    }
    if (this.isStrEmpty(this.personalInfo.sex)) {

      this.showDialog('性别不能为空，请填写性别');
      this.timing();

      return;
    }
    if (this.isStrEmpty(this.personalInfo.grade)) {
      this.showDialog('期数不能为空，请填写期数');
      this.timing();
      return;
    }
    if (this.isStrEmpty(this.personalInfo.email)) {
      this.showDialog('邮箱不能为空，请填写邮箱');
      this.timing();
      return;
    }
    let emailFormat = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    if (emailFormat.test(this.personalInfo.email) == false) {
      this.showDialog('邮箱格式不规范');
      this.timing();
      return;
    }

    let addUrl = "graduate-web/personalInfo/addPersonInfo/";
    let body = JSON.stringify(this.personalInfo);
    console.log(body + "执行我!执行我!");
    this.http.post(addUrl, body).toPromise().then(
      res => {
        if (res.json().code = "0000") {
          console.log(res.json().code);
          this.showDialog("您的信息添加成功！");
          this.timing();
          this.close(addModal);
          // this.combinationSearch();
          this.getData();
        }
      }
    );
  }

  display: boolean = false;
  messages: "";

  /**
     * 提示框
     */
  showDialog(string) {
    this.messages = string;
    this.display = true;
  }

  closeDialog() {
    this.display = false;
  }

  // 定时关闭弹出框
  timing() {
    this.timer = setInterval(() => {
      this.identificateTime = this.identificateTime - 1;
      if (this.identificateTime <= 0) {
        // clearInterval(this.timer);
        this.closeDialog();
      }
    }, 1000);
    this.identificateTime = 5;
  }
  // 打开修改模态框
  editOpen(index: any, editModal: HTMLElement) {
    editModal.style.visibility = 'visible';
    this.personalInfo.name = this.data[index].name;
    this.personalInfo.sex = this.data[index].sex;
    this.personalInfo.grade = this.data[index].grade;
    this.personalInfo.email = this.data[index].email;
    this.personalInfo.id = this.data[index].id;
    document.getElementById('name').focus();
    localStorage.setItem('studentId', this.personalInfo.id);
  }

  gainStudentId(index: any, editModal: HTMLElement) {
    this.personalInfo.id = this.data[index].id;
    localStorage.setItem('studentId', this.personalInfo.id);
  }
  // 修改信息
  update(editModel: HTMLElement, modal: HTMLElement) {
    let editUrl = 'graduate-web/personalInfo/updatePersonInfo/';
    // let userId = 'SdHAYGfnaGYJa68TenWzPm'; // 假数据，从登陆信息获取
    // this.personalInfo.id = userId;
    console.log(this.personalInfo.id + "woshiid");
    let body = JSON.stringify(this.personalInfo);
    this.http.post(editUrl, body).toPromise().then(
      res => {
        if (res.json().code = '0000') {
          this.showDialog(res.json().message);
          // this.combinationSearch();
          this.timing();
          this.getData();

          this.close(editModel);
          console.log(res.json() + '！！！！！');
        }

      }
    );
  }
  /*********************添加修改模态框End************************/

  /**********************文件导入start********************** */
  //打开导入框
  import(info: any) {
    this.filename = "";
    this.displayFile = true;
    // 打开导入框时清除之前选择的文件记录
    let e: any = document.getElementById('filePath');
    e.value = "";
    this.uploader.clearQueue();
  }

  /**
   * 显示选择文件的框
   */
  show(el: HTMLElement) {
    el.click();
  }

  //选择文件后触发的事件
  selectedFileOnChanged(event: any) {
    this.filename = event.target.value;
  }
  // 关闭模态框
  close(modal: HTMLElement) {
    modal.style.visibility = 'hidden';
    this.personalInfo = new PersonalInfoEntity();
  }


  public uploader: FileUploader = new FileUploader({
    url: this.http.getServerUrl("graduate-web/personalInfo/importPersonExcel"),
    method: "POST"

  });

  filename = "";//页面显示的文件名

  displayFile: boolean = false;

  //上传触发事件
  upload() {
    if (this.filename == "") {
      this.showDialog("没有选择文件，请选择文件");
      return;
    }
    let extName = this.filename.substring(this.filename.lastIndexOf('.') + 1);
    if (extName == "xls" || extName == "xlsx") {
      this.uploadFile();
      this.displayFile = false;
    } else {
      this.showDialog("文件类型不正确，请选择正确的Excel文件（.xls|.xlsx）");
    }
  }

  // //文件上传执行事件
  uploadFile() {
    let obj = this;
    this.uploader.queue[this.uploader.queue.length - 1].upload();

    this.uploader.queue[this.uploader.queue.length - 1].onSuccess = function (response, status, headers) {
      if (status == 200) {
        let tempRes = JSON.parse(response);
        if (tempRes.code == "0000") {
          obj.showDialog(tempRes.message);
        } else if (tempRes.code == "1111") {
          obj.showDialog(tempRes.message);
          // document.getElementById('btnErrorDataShow').setAttribute('style', 'display:visible');
        } else {
          obj.showDialog("文件数据存在无效值，请检查数据格式");
        }
        obj.getData();
      }
      else {
        obj.showDialog("与服务连接异常，请重试！");
      }
    };
  }

  /**********************文件导入end********************** */
  /**********************导出模板start*************************/
  /**
 * 下载模板
 */
  down() {
    let url = 'graduate-web/personalInfo/exportExcel';
    url = this.http.getServerUrl(url);
    this.http.get(url).subscribe(
      res => {
        if (res.status == 200) {
          window.open(url);
          URL.revokeObjectURL(url);
        } else {
          this.showDialog('下载文件失败，请稍后尝试！');
        }
      });
  }

  /**************************导出模板End********************************/


  /**
   *modal框可拖拽
  */
  draggable() {
    $('.modal-dialog').draggable();
  }
}
// , input: HTMLInputElement

export class Condition {
  personName?: String
  companyName?: String
  educationName?: String
  gradeName?: String
  salaryRange?: String
}